import { _decorator, Component, Node, AudioSource, Sprite, BoxCollider2D, Collider2D, Contact2DType, AudioClip, instantiate, Vec2, Vec3 } from 'cc';
import { Battle } from '../Battle';
import { EnDynamicLineType } from '../Common/const/EnCommon';
import { EnEvent } from '../Common/const/EnEvent';
import { GameAPI } from '../Common/GameAPI';
import { Utitls } from '../Common/Utils';
import { Enum_AudioClip } from '../Enum';
import { ResourcesUtil } from '../ResourcesUtil';
const { ccclass, property } = _decorator;

@ccclass('TreeController')
export class TreeController extends Component {

    @property(Node)
    private treeEnergyPrefab: Node = null;

    // 经验
    private totalExp: number = 2;
    private _audioSound: AudioSource;
    private _cutAudio: AudioClip = null;

    private rebornTime: number = 30;
    private isCut: boolean = false;

    private mySprite: Sprite;
    private boxCollider2D: BoxCollider2D;

    private curExp: number = 0;
    private isTrigger: boolean = false;

    private initPosX: number = 0;
    private initPosY: number = 0;

    private treeEnergyPos: Array<Vec3> = [];

    public isDie: boolean = false;
    private bulletHitList: Array<string> = [];

    private obstacle: Node;

    async start() {
        this.isTrigger = true;
        this.mySprite = this.node.getComponent(Sprite);
        this.boxCollider2D = this.node.getComponent(BoxCollider2D);
        this.boxCollider2D.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        // 音频
        this._audioSound = this.node.getComponent(AudioSource);
        this._cutAudio = await ResourcesUtil.loadAudioClip(Enum_AudioClip.Thetreefell);
        this.curExp = this.totalExp;
        this.initPosX = this.node.position.x;
        this.initPosY = this.node.position.y;
        //首次
        this.treeEnergyPos.push(new Vec3(this.initPosX - 63, this.initPosY - 97, 0));
        this.treeEnergyPos.push(new Vec3(this.initPosX + 20, this.initPosY - 118, 0));
        //第二次
        this.treeEnergyPos.push(new Vec3(this.initPosX - 63, this.initPosY - 97, 0));
        this.treeEnergyPos.push(new Vec3(this.initPosX + 32, this.initPosY - 117, 0));
        this.treeEnergyPos.push(new Vec3(this.initPosX - 23, this.initPosY - 136, 0));
        this.treeEnergyPos.push(new Vec3(this.initPosX - 10, this.initPosY - 70, 0));
        this.bulletHitList.push("Player_Bullet_1");
        this.bulletHitList.push("Player_Bullet_2");
        this.bulletHitList.push("Player_Bullet_3");
        this.bulletHitList.push("Player_Bullet_4");
        this.bulletHitList.push("Player_Bullet_5");
        let intervals = [1, 1.2, 1.4, 1.6];
        let intervalTime = intervals[Utitls.Random(0, intervals.length - 1)];
        let myThis = this;
        this.scheduleOnce(function () {
            myThis.GetObstacle();
        }.bind(this), intervalTime);
    }

    GetObstacle() {
        let minDistance = 1000;
        let myPoint = this.node;
        let point = this.node.getChildByName("Point");
        if (point) {
            myPoint = point;
        }
        let worldPos = this.node.getWorldPosition();
        for (let index = 0; index < Battle.PolygonNav2D.children.length; index++) {
            const element = Battle.PolygonNav2D.children[index];
            const distance = Vec2.distance(element.getWorldPosition(), worldPos);
            if (distance < minDistance) {
                minDistance = distance;
                this.obstacle = element;
            }
        }
    }

    onEnable() {
        this.curExp = this.totalExp;
        this.isTrigger = true;
        this.isDie = false;
        
    }

    onDisable() {
        this.isDie = true;
    }

    // 碰撞开始回调函数
    onBeginContact(self: Collider2D, other: Collider2D) {
        for (let index = 0; index < this.bulletHitList.length; index++) {
            const element = this.bulletHitList[index];
            if (other.node.name == element) {
                this.StartCut();
                console.log("子弹击中树");
                break;
            }
        }
    }

    StartCut() {
        this._audioSound.playOneShot(this._cutAudio);
        this.curExp -= 1;
        // GameAPI.FireGEvent(EnEvent.PlayerEnergyAdd, { type: 1, num: 2 });
        let maxCount = 2;
        let startIndex = 0;
        if (this.curExp == 1) {
            startIndex = 0;
        }
        else {
            startIndex = 2;
            maxCount = 4;
        }
        for (let index = startIndex; index < this.treeEnergyPos.length; index++) {
            if (maxCount <= 0) {
                break;
            }
            this.CreatorChatItem(index);
            maxCount = maxCount - 1;
        }
        if (this.curExp <= 0) {
            GameAPI.FireGEvent(EnEvent.RemovePolygonEvent, { obstacle: this.obstacle.name });
            this.UpdateCutState();
        }
    }

    CreatorChatItem(posIndex: number) {
        let obj = instantiate(this.treeEnergyPrefab);
        Battle.EnergyObjParent.addChild(obj);
        if (posIndex >= this.treeEnergyPos.length) {
            posIndex = this.treeEnergyPos.length - 1;
        }
        let pos = this.treeEnergyPos[posIndex];
        obj.setPosition(pos);
        obj.active = true;
    }

    private UpdateCutState() {
        this.isCut = true;
        this.scheduleOnce(this.ResetState.bind(this), this.rebornTime);
        this.CutState();
    }

    CutState() {
        // this.mySprite.enabled = !this.isCut;
        // this.boxCollider2D.enabled = !this.isCut;
        if (this.isCut) {
            // this.node.setPosition(200000, 200000);
            this.node.active = false;
            GameAPI.FireGEvent(EnEvent.GuideTipEvent, { index: 1, active: false });
            GameAPI.FireGEvent(EnEvent.GuideTipEvent, { index: 3, active: true });
            if (!Battle.IsFirstTree) {
                GameAPI.FireGEvent(EnEvent.DynamicLineEvent, { type: EnDynamicLineType.Default });
                Battle.IsFirstTree = true;
            }
        }
        else {
            this.node.setPosition(this.initPosX, this.initPosY);
        }
    }

    ResetState() {
        this.isCut = false;
        this.curExp = this.totalExp;
        this.CutState();
    }

}


